package org.flik.client.main;

import org.flik.client.main.service.UserServiceAsync;
import org.flik.client.shared.ClientUtils;
import org.flik.client.shared.CommonAsyncCallback;
import org.flik.server.dto.TicketSummary;
import org.flik.server.dto.TiketSearchResult;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.SimplePager.TextLocation;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.ResizeComposite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
import com.google.gwt.view.client.SingleSelectionModel;

public class TicketSearchResultGrid extends ResizeComposite {

	private static TicketSearchResultGridUiBinder uiBinder = GWT.create(TicketSearchResultGridUiBinder.class);

	private static final int SEARCH_RESULT_DATAGRID_PAGE_SIZE = 15;

	interface TicketSearchResultGridUiBinder extends UiBinder<Widget, TicketSearchResultGrid> {
	}

	@UiField(provided = true)
	SimplePager pager;

	@UiField(provided=true)
	DataGrid<TicketSummary> dataGrid; 
	
	private AsyncDataProvider<TicketSummary> dataProvider;
	
	private Long projectId; 
	
	public TicketSearchResultGrid() {
		initDataGrid();
		initPager();
		initWidget(uiBinder.createAndBindUi(this));
		initDataProvider();
		setSelectionModel();
		addColumns();
		dataGrid.setAutoHeaderRefreshDisabled(true);
		setWidth("100%");
	}

	private void initDataGrid() {
		dataGrid = new DataGrid<TicketSummary>(SEARCH_RESULT_DATAGRID_PAGE_SIZE, new ProvidesKey<TicketSummary>(){

			@Override
			public Object getKey(TicketSummary item) {
				return item.getTicketId();
			}});
	}
	private void initDataProvider(){
		dataProvider = new AsyncDataProvider<TicketSummary>() {
			
			@Override
			protected void onRangeChanged(HasData<TicketSummary> display) {//On range changed will be fired at initialization.  
				fetchAndSetTicketSearchResult(display.getVisibleRange().getStart());
			}
		};
		dataProvider.addDataDisplay(dataGrid);
	}
	
	public void refreshData(Long projectId){
		this.projectId = projectId;
		fetchAndSetTicketSearchResult(0);
	}
	
	private void fetchAndSetTicketSearchResult(final int start){
		if (projectId != null){
			ClientUtils.showRemoteCommunicationMessage("loading...");
			UserServiceAsync.INSTANCE.fetchTicketSearchResult(projectId, start, SEARCH_RESULT_DATAGRID_PAGE_SIZE, new CommonAsyncCallback<TiketSearchResult>() {
				
				@Override
				public void onSuccess(TiketSearchResult result) {
					ClientUtils.hideRemoteCommunicationMessage();
					
					dataGrid.setPageStart(start);
					dataGrid.setRowData(start, result.getTickets());
					dataGrid.setRowCount(result.getMaxResults());
				}
			});
		}
	}

	private SingleSelectionModel<TicketSummary> selectionModel = new SingleSelectionModel<TicketSummary>();
	private void setSelectionModel() {
		dataGrid.setSelectionModel(selectionModel);
	}
	private void initPager(){
		SimplePager.Resources pagerResources = 
				GWT.create(SimplePager.Resources.class);
		pager = new SimplePager(
				TextLocation.CENTER, 
				pagerResources, 
				false, 0, true);
		pager.setPageSize(SEARCH_RESULT_DATAGRID_PAGE_SIZE);
		pager.setDisplay(dataGrid);
	}

	public TicketSummary getSelectedTicket(){
		return selectionModel.getSelectedObject();
	}
	
	public void addSelectionHandler(Handler handler){
		selectionModel.addSelectionChangeHandler(handler);
	}
	
	private void addColumns() {
		dataGrid.addColumn(new TextColumn<TicketSummary>() {

			@Override
			public String getValue(TicketSummary object) {
				return object.getTicketId().toString();
			}
		}, "#");
		
		dataGrid.addColumn(new TextColumn<TicketSummary>() {

			@Override
			public String getValue(TicketSummary object) {
				return object.getTicketTitle();
			}
		}, "Ticket Title");

		dataGrid.addColumn(new TextColumn<TicketSummary>() {
			
			@Override
			public String getValue(TicketSummary object) {
				return object.getTicketTypeDesc();
			}
		}, "Type");
		
		dataGrid.addColumn(new TextColumn<TicketSummary>() {

			@Override
			public String getValue(TicketSummary object) {
				return object.getTicketStatusDesc();
			}
		}, "Status");

		dataGrid.addColumn(new TextColumn<TicketSummary>() {

			@Override
			public String getValue(TicketSummary object) {
				return object.getReportedByFullName();
			}
		}, "Reported By");

		dataGrid.addColumn(new TextColumn<TicketSummary>() {

			@Override
			public String getValue(TicketSummary object) {
				return object.getAssigneeFullName();
			}
		}, "Assigned To");

	    // Checkbox column. This table will use a checkbox column for selection.
	    // Alternatively, you can call cellTable.setSelectionEnabled(true) to enable
	    // mouse selection.
	    Column<TicketSummary, Boolean> checkColumn = new Column<TicketSummary, Boolean>(
	        new CheckboxCell(true, false)) {
	      @Override
	      public Boolean getValue(TicketSummary object) {
	        // Get the value from the selection model.
	        return selectionModel.isSelected(object);
	      }
	    };
	    dataGrid.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));

	}
//	public abstract void onTicketEdit(TicketSummary ticket);
}
